import { createRouter, createWebHistory } from 'vue-router';
import store from '@/store/index.js';
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      name: 'layout',
      component: () => import('@/layout/index.vue'),
      meta: {
        auth: true,
      },
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/login/index.vue'),
    },
  ],
});
router.beforeEach((to, from, next) => {
  const token = store.getters.token;
  if (token) {
    store.dispatch('user/getUserInfo');
  }
  if (to.path === '/login') {
    if (token) {
      next({ path: '/dashboard' });
      return;
    }
  }
  if (to.meta.auth) {
    if (token) {
      next();
    } else {
      next({ path: '/login' });
    }
    return;
  }
  next();
});

export default router;
